<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="产品名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入所属分类"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上下架" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择上下架" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" border size="mini" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" v-if="false"/>
      <el-table-column label="产品名" align="center" prop="name" />
      <el-table-column label="所属分类" align="center" prop="courseName" />
      <el-table-column label="封面图" align="center" prop="picUrl" >
        <template slot-scope="scope">
          <img :src="scope.row.picUrl" alt="封面图" height="100%" width="100%"  v-if="scope.row.picUrl" @click="showImg(scope.row.picUrl)">
        </template>
      </el-table-column>
      <el-table-column label="详情图" align="center" prop="detailUrl" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-picture"  v-if="scope.row.detailUrl"
            @click="showImg(scope.row.detailUrl)"
          >点击查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="摘要" align="center" prop="digest" >
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="300"
            trigger="hover"
            :disabled="scope.row.digest.length <= 4"
          >
            <div>{{ scope.row.digest }}</div>
            <span slot="reference" v-if="scope.row.digest.length <= 4">{{scope.row.digest}}</span>
            <span slot="reference" v-if="scope.row.digest.length > 4">{{scope.row.digest.substr(0, 4) + "..."}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="停车场id" align="center" prop="parkId" />
      <el-table-column label="产品规格" align="center" prop="attribute" />
      <el-table-column label="产品库存" align="center" prop="stock" />
      <el-table-column label="市场价格" align="center" prop="price" >
        <template slot-scope="scope">
          <span>{{scope.row.price / 100}}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠价格" align="center" prop="preferentialPrice" >
        <template slot-scope="scope">
          <span>{{scope.row.preferentialPrice / 100}}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="详情" align="center" prop="productDetail" >
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="300"
            trigger="hover" v-if="scope.row.productDetail"
            :disabled="scope.row.productDetail.length <= 4"
          >
            <div>{{ scope.row.productDetail }}</div>
            <span slot="reference" v-if="scope.row.productDetail.length <= 4">{{scope.row.productDetail}}</span>
            <span slot="reference" v-if="scope.row.productDetail.length > 4">{{scope.row.productDetail.substr(0, 4) + "..."}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="销量" align="center" prop="sellNum" />
      <el-table-column label="月卡时长" align="center" prop="duration" />
      <el-table-column label="添加时间" align="center" prop="createtime" width="135">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updatetime" width="135">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatetime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上下架" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" fixed="right" width="130" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 图片列表 -->
    <el-dialog :title="imgTitle" :visible.sync="imgOpen" v-if="imgOpen" width="40%" append-to-body>
      <show-imgs :imgs="imgUrl"></show-imgs>
    </el-dialog>
    <!-- 添加或修改服务产品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules"   label-width="120px">
        <el-form-item label="产品名" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名" />
        </el-form-item>
        <el-form-item label="产品摘要" prop="digest">
          <el-input v-model="form.digest" placeholder="请输入产品摘要" />
        </el-form-item>
        <el-form-item label="产品类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择产品类型" clearable style="width: 100%">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="市场价格" prop="price">
          <el-input-number :min="0" :step="0.01" v-model="form.price" placeholder="请输入产品市场价格"  style="width: 100%"/>
        </el-form-item>
        <el-form-item label="优惠价格" prop="preferentialPrice">
          <el-input-number :min="0" :step="0.01" v-model="form.preferentialPrice" placeholder="请输入产品优惠价格"  style="width: 100%"/>
        </el-form-item>
        <el-form-item label="产品规格" prop="attribute">
          <el-input v-model="form.attribute" placeholder="请输入产品规格" />
        </el-form-item>
        <el-form-item label="产品库存" prop="stock">
          <el-input-number :min="1" :step="1" v-model="form.stock" placeholder="请输入产品库存"  style="width: 100%"/>
        </el-form-item>
        <div v-if="form.type == 1">
          <el-form-item label="月卡时长" prop="duration">
            <el-input-number :min="1" v-model="form.duration" placeholder="请输入月卡时长" style="width: 100%"/>
          </el-form-item>
          <el-form-item label="关联停车场" prop="parkId">
            <el-select v-model="form.parkId" style="width: 100%"  placeholder="请选择关联停车场" filterable clearable size="small" >
              <el-option
                v-for="park in parkListOptions"
                :key="park.id"
                :label="park.parkName"
                :value="Number(park.id)"
              />
            </el-select>
          </el-form-item>
        </div>
        <div v-if="form.type == 2">
          <el-form-item label="所属分类" prop="parentId">
            <el-select v-model="form.parentId" clearable filterable  placeholder="父级分类" style="width: 50%" @change="getListByParent(form.parentId)">
              <el-option
                v-for="dict in parentClassListOption"
                :key="dict.id"
                :label="dict.title"
                :value="parseInt(dict.id)"
              ></el-option>
            </el-select>
            <el-select v-model="form.courseId" clearable filterable  placeholder="二级分类" style="width: 50%" >
              <el-option
                v-for="dict in classListByParentOption"
                :key="dict.id"
                :label="dict.title"
                :value="parseInt(dict.id)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="封面图地址">
            <imageUpload v-model="form.picUrl" @removeImage="removeImage(form.picUrl)" @input="getUrl"/>
          </el-form-item>
          <el-form-item label="详情图地址">
            <upload-img v-model="form.detailUrl"></upload-img>
          </el-form-item>
        </div>
        <el-form-item label="产品描述" prop="productDetail">
          <editor v-model="form.productDetail" :min-height="192"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, exportProduct } from "@/api/system/product";
import ImageUpload from '@/components/ImageUpload';
import moreImgUpload from '@/components/moreImgUpload';
import Editor from "../../../components/Editor";
import { getParkList} from "@/api/system/park";
import { parentClassList,getListByParent } from "@/api/system/course";
import UploadImg from "@/components/UploadImg";
import ShowImgs from "@/components/ShowImgs";
export default {
  name: "Product",
  components: {
    ShowImgs,
    UploadImg,
    ImageUpload,moreImgUpload,Editor
  },
  data() {
    return {
	  //按钮loading
	  buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务产品管理表格数据
      productList: [],
      // 弹出层标题
      title: "",
      imgOpen: false,
      imgUrl: "",
      imgTitle: "",
      // 是否显示弹出层
      open: false,
      // 产品类型字典
      typeOptions: [],
      //根据类型获取的一级分类列表
      parentClassListOption: [],
      //根据一级分类获取的二级分类列表
      classListByParentOption: [],
      // 上下架字典
      statusOptions: [],
      // 停车场列表
      parkListOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        digest: undefined,
        courseId: undefined,
        parkId: undefined,
        detailUrl: undefined,
        picUrl: undefined,
        attribute: undefined,
        stock: undefined,
        price: undefined,
        preferentialPrice: undefined,
        type: undefined,
        productDetail: undefined,
        sellNum: undefined,
        duration: undefined,
        createtime: undefined,
        updatetime: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        price: [
          { required: true, message: "产品市场价格不能为空", trigger: "blur" }
        ],
        preferentialPrice: [
          { required: true, message: "产品优惠价格不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getParentClassList();
    this.getParkList();
    this.getDicts("product_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("product_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询服务产品管理列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getParkList(){
      let data={}
      getParkList(data).then(response => {
        this.parkListOptions = response.data;
      });
    },
    //获取父级分类列表
    getParentClassList(){
      this.form.parentId = null;
      this.queryParams.parentId = null;
      var data = {
        parentId:0,
        grade:1
      };
      parentClassList(data).then(response => {
        this.parentClassListOption = response.data;
      });
    },
    //获取父级分类列表
    getListByParent(parentId){
      this.form.courseId = null;
      this.queryParams.courseId = null;
      var data = {
        parentId:parentId,
        grade:2
      };
      getListByParent(data).then(response => {
        this.classListByParentOption = response.data;
      });
    },
    // 产品类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 上下架字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.imgOpen = false;
      this.reset();
    },
    //查看封面图
    showImg(imgUrl) {
      this.imgOpen = true;
      this.imgTitle = "查看封面图";
      this.imgUrl = imgUrl;
    },

    removeImage(value){
      if (value){
        this.form.picUrl = this.form.picUrl.replace(value,'')
      }

    },
    getUrl(url) {
      if (url) {
        this.form.picUrl = url;
      }
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        digest: undefined,
        courseId: undefined,
        parkId: undefined,
        detailUrl: undefined,
        picUrl: undefined,
        attribute: undefined,
        stock: undefined,
        price: undefined,
        preferentialPrice: undefined,
        type: undefined,
        productDetail: undefined,
        sellNum: undefined,
        duration: undefined,
        createtime: undefined,
        updatetime: undefined,
        status: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务产品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.loading = false;
        this.getListByParent(response.data.parentId)
        this.form = response.data;
        this.form.preferentialPrice = this.form.preferentialPrice / 100
        this.form.price = this.form.price / 100
        this.open = true;
        this.title = "修改服务产品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.preferentialPrice = this.form.preferentialPrice * 100
          this.form.price = this.form.price * 100
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除服务产品管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delProduct(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有服务产品管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportProduct(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
